package com.wzs.rpc.fault.tolerant;

import com.wzs.rpc.loadbalancer.LoadBalancer;
import com.wzs.rpc.loadbalancer.RoundRobinLoadBalancer;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

@Slf4j
public class TolerantStrategyFactory {
    private static final Map<String, Object> instanceCache = new HashMap<>();
    private static final TolerantStrategy DEFAULT_TOLERANT_STRATEGY = new FailFastTolerantStrategy();

    //饿汉，加载时便初始化，避免多线程下的安全问题
    static {
        ServiceLoader<TolerantStrategy> tolerantStrategies = ServiceLoader.load(TolerantStrategy.class);
        for (TolerantStrategy tolerantStrategy : tolerantStrategies) {
            instanceCache.put(tolerantStrategy.getClass().getName(), tolerantStrategy);
        }
        log.debug("SPI加载LoadBalancer, 实例个数为 {}", instanceCache.size());
    }

    public static TolerantStrategy getInstance(String tolerantStrategy) {
        return (TolerantStrategy) instanceCache.getOrDefault(tolerantStrategy, DEFAULT_TOLERANT_STRATEGY);
    }
}
